<?php

class Money_Model_DbTable_Money extends Engine_Db_Table {

    protected $_rowClass = 'Money_Model_Money';

    public function insertUser() {
        $viewer = Engine_Api::_()->user()->getViewer();

        $row = $this->fetchRow($this->select()->where('user_id = ?', $viewer->getIdentity()));
        if (!$row) {
            $user = $this->createRow();
            $user->user_id = $viewer->getIdentity();
            $user->save();
        }
    }

    public function getMoney() {
        $viewer = Engine_Api::_()->user()->getViewer();

        $row = $this->fetchRow($this->select()->where('user_id = ?', $viewer->getIdentity()));
        return $row ? $row->money : 0;
    }

    public function updateMoney($recip, $amount) {
        $viewer = Engine_Api::_()->user()->getViewer();
        $row = $this->fetchRow($this->select()->where('user_id = ?', $viewer->getIdentity()));

        $row->money = $row->money - $amount;
        $row->save();

        $row1 = $this->fetchRow($this->select()->where('user_id = ?', $recip));
        $row1->money = $row1->money + $amount;
        $row1->save();
    }

    public function updateMoneyPayPal(User_Model_User $user, $amount) {
        $commission = Engine_Api::_()->getApi('settings', 'core')->getSetting('money.commission');

        $new_amount = $amount - ($amount * $commission) / 100;

        $row = $this->fetchRow($this->select()->where('user_id = ?', $user->getIdentity()));
        $row->money = $row->money + $new_amount;
        $row->save();
    }

   
    
    public function setMoney($user_id, $amount){
        $row = $this->fetchRow($this->select()->where('user_id = ?', $user_id));
       
        if(!$row){
            $row = $this->createRow();
            $row->user_id = $user_id;
            $row->save();
        }
        
        $row->money = $row->money + $amount;
        $row->save();
    }
    
    

    

}